module Common where
import Control.Monad

data Tree a = Node (Tree a) a (Tree a) | Nil

tree = Node (Node Nil 1 Nil) 0 (Node Nil 2 Nil)

treeSum :: (Num a) => Tree a -> a
treeSum Nil = 0
treeSum (Node l v r) = treeSum l + treeSum r + v

instance (Show a) => Show (Tree a) where
  showsPrec _ = treeShows

treeShows :: (Show a) => Tree a -> ShowS
treeShows Nil = showString "Nil"
treeShows (Node l v r) = showChar '<' . treeShows l . showChar '{' . 
  shows v . showChar '}' . treeShows r . showChar '>'

instance (Read a) => Read (Tree a) where
  readsPrec _ = treeRead

treeRead::(Read a) => String -> [(Tree a, String)]
treeRead ('<':xs) = [(Node lVal nVal rVal, rStr) | (lVal, '{':lStr) <- treeRead xs,
                                                   (nVal, '}':nStr) <- reads lStr,
                                                   (rVal, '>':rStr) <- treeRead nStr]
treeRead ('N':'i':'l':xs) = [(Nil, xs)]

{-main :: IO ()
main = do
  return $ treeSum tree;
  return ();-}
